<template>
  <div id="show-chat" class="show-chats scroll" @scroll="newPage">
    <!-- 消息 -->
    <!-- 右键显示消息撤回和转发 -->
    <!-- <div class="chat-item" v-for="(chat, index) in chats" :key="index" @contextmenu.prevent="rightEvent($event,chat)" > -->
    <div class="chat-item" v-for="(chat, index) in chats" :key="index">
      <!-- 时间 -->
      <div
        class="chat-time"
        v-text="$options.filters.timeFilter(chat.CreateTime)"
      ></div>
      <!-- 内容 -->
      <div
        class="chat-content"
        :class="{ 'chat-content-send': chat.IsSend ? true : false }"
      >
        <!-- 头像 -->
        <el-avatar
          shape="square"
          v-if="notShow.indexOf(chat.ContentType) === -1"
          :size="40"
          :src="getAvatar(chat)"
          @error="
            () => {
              return true;
            }
          "
          @click.native="showMemberDetail(chat)"
          title="头像"
        >
          <img
            src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
          />
        </el-avatar>

        <!-- 群成员id -->
        <div
          class="member-info"
          v-if="
            currentFriend.UserName &&
            !chat.IsSend &&
            notShow.indexOf(chat.ContentType) === -1
          "
        >
          <span v-text="getMemberName(chat.Content)"></span>
          <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            type="plant"
            size="mini"
            @click="atSomebody(chat)"
            >@Ta</el-button
          >
          <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            v-if="
              currentFriend.Owner && currentFriend.Owner === currentWeChatId
            "
            type="plant"
            size="mini"
            :disabled="knicking"
            :loading="knicking"
            @click="knickSomeBody(chat)"
            >踢人</el-button
          >
        </div>

        <!-- content -->
        <div
          class="content-content"
          :class="[
            {
              'triangle-send':
                chat.IsSend && notShow.indexOf(chat.ContentType) === -1,
            },
            {
              triangle:
                notShow.indexOf(chat.ContentType) === -1 && !chat.IsSend,
            },
            {
              'chat-room':
                currentFriend.UserName &&
                !chat.IsSend &&
                notShow.indexOf(chat.ContentType) === -1,
            },
            { 'system-info': notShow.indexOf(chat.ContentType) > -1 },
          ]"
        >
          <div
            :class="[
              {
                'chat-picture':
                  chat.ContentType === 'Picture' || chat.ContentType === 2,
              },
              {
                'chat-voice':
                  chat.ContentType === 'Voice' || chat.ContentType === 3,
              },
              {
                'chat-video':
                  chat.ContentType === 'Video' || chat.ContentType === 4,
              },
              {
                'chat-link':
                  chat.ContentType === 'Link' || chat.ContentType === 6,
              },
              {
                'chat-file':
                  chat.ContentType === 'File' || chat.ContentType === 8,
              },
              {
                'chat-namecard':
                  chat.ContentType === 'NameCard' || chat.ContentType === 9,
              },
              {
                'chat-luckmoney':
                  chat.ContentType === 'LuckyMoney' || chat.ContentType === 11,
              },
              {
                'chat-moneytran':
                  chat.ContentType === 'MoneyTrans' || chat.ContentType === 12,
              },
              {
                'chat-app':
                  chat.ContentType === 'WeApp' || chat.ContentType === 13,
              },
              { 'chat-system': notShow.indexOf(chat.ContentType) > -1 },
            ]"
            v-html="decodeChat(chat)"
            @click="whatToDo(chat)"
          ></div>
        </div>

        <!-- 发送结果 -->
        <div
          class="send-state"
          :class="{
            'chat-room':
              currentFriend.UserName &&
              !chat.IsSend &&
              notShow.indexOf(chat.ContentType) === -1,
          }"
        >
          <!-- 发送状态 -->
          <el-button
            type="text"
            v-if="chat.IsSend && !chat.msgSvrId"
            class="el-icon-loading"
          ></el-button>
          <!-- 已经撤销 -->
          <el-button
            type="text"
            style="margin-left: 10px; color: #e6a23c; padding: 5px"
            v-if="chat.revoked"
            class="el-icon-info"
            title="已撤回"
            >已撤回</el-button
          >
          <!-- 撤回 -->
          <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            v-if="
              chat.IsSend &&
              chat.msgSvrId &&
              !chat.revoked &&
              revokeMap.indexOf(chat.ContentType) >= 0 &&
              chat.canRevoke
            "
            type="plant"
            size="mini"
            :loading="revoking"
            :disabled="revoking"
            @click="revokeMessageTask(chat)"
            >撤回</el-button
          >
          <!-- 转发 -->
          <!-- <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            v-if="chat.msgSvrId && revokeMap.indexOf(chat.ContentType) >= 0"
            type="plant"
            size="mini"
            class="el-icon-s-promotion"
            @click="canTransform(chat)"
            >转发</el-button
          > -->
          <!-- 添加收款码 -->
          <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            v-if="chat.ContentType === 'Picture' &&!chat.IsSend &&rebatesChannel ==0 &&showAddWxPaymentcode"
            type="plant"
            size="mini"
            class="el-icon-folder-add"
            @click="addWxPaymentcode(chat)"
            >添加收款码</el-button
          >
        </div>
      </div>
    </div>
    <div v-if="chats.length === 0" class="chat-no"></div>
    <!-- 大图 -->
    <el-dialog
      class="detail-dialog"
      title="详情"
      :visible.sync="detailDialogVisible"
      width="30%"
      :before-close="handleDeatilClose"
    >
      <!-- 图片 -->
      <el-image
        class="detail-dialog-img"
        v-if="
          detailUrl &&
          (detailUrl.endsWith('.png') ||
            detailUrl.endsWith('.jpg') ||
            detailUrl.endsWith('.gif'))
        "
        :src="detailUrl"
      >
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
      <!-- 视频 -->
      <video
        class="detail-dialog-video"
        v-else-if="detailUrl && detailUrl.endsWith('.mp4')"
        :src="detailUrl"
        controls
      ></video>
      <!-- 文件 -->
      <a v-else-if="detailUrl" target="_blank" :href="detailUrl">点击下载</a>
      <span v-else>
        <i class="el-icon-loading"></i>
        正在获取详情
      </span>
    </el-dialog>
    <!-- 群成员详情 -->
    <el-dialog
      class="member-detail"
      title="群成员详情"
      :visible.sync="memberDialog"
    >
      <div class="member-detail-info">
        <el-avatar
          shape="square"
          :size="100"
          :src="memberDetail.Avatar"
          @error="errorHandler"
        >
          <img
            src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
          />
        </el-avatar>
        <div class="member-detail-text">
          <p>
            微信：
            <span v-text="memberDetail.FriendId"></span>
          </p>
          <p>
            昵称：
            <span v-text="memberDetail.FriendNick || '- -'"></span>
          </p>
          <p>
            性别：
            <span v-text="memberDetail.Gender || '- -'"></span>
          </p>
          <p>
            地址：
            <span v-text="memberDetail.Province || '-'"></span>
            &nbsp;
            <span v-text="memberDetail.City || '-'"></span>
          </p>
        </div>
      </div>
      <div class="member-detail-btns">
        <el-button
          v-if="!friendMap[memberDetail.FriendId]"
          type="primary"
          size="medium"
          @click="getMemberDetail"
          >获取详情</el-button
        >
        <el-button
          v-if="!friendMap[memberDetail.FriendId]"
          type="primary"
          size="medium"
          @click="addToAddress"
          >添加到通讯录</el-button
        >
      </div>
    </el-dialog>
    <!-- 红包详情 -->
    <el-dialog
      class="hb-details"
      title="红包详情"
      :visible.sync="hbDetailVisible"
    >
      <ul class="hb-detail">
        <li>当前微信：{{ hbDetail.WeChatId }}</li>
        <li>红包来源：{{ hbDetail.HbUrl | hbUrlFilter }}</li>
        <li>红包总数：{{ hbDetail.TotalNum }}</li>
        <li>红包总金额：{{ hbDetail.TotalAmount }}</li>
        <li>已抢的数量：{{ hbDetail.RecNum }}</li>
        <li>已抢的金额：{{ hbDetail.RecAmount }}</li>
        <li>
          抢红包的好友列表
          <ul>
            <li v-for="(item, index) in hbDetail.Records" :key="index">
              <div>{{ item }}</div>
            </li>
          </ul>
        </li>
      </ul>
      <div class="hb-btns">
        <el-button type="info" size="small" @click="hbDetailVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="takeLuckMoney(hb2detail)"
          >打开红包</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'

import phiz from '@/common/phiz.js'
import base64 from '@/common/base64.js'

export default {
  data() {
    return {
      // page: 0,
      // currentTime: new Date().getTime(), // 当前的时间 用来判断消息能不能撤销
      size: 10,
      notShow: ['System', 'Sys_LuckyMoney', 'RoomSystem', 5, 16, 17], // 符合条件的将不显示头像
      revokeMap: ['Text', 'NameCard', "Picture", "Voice", "Video", "File", "Link", 'WeApp'], // 符合的才显示撤回按钮
      detailDialogVisible: false, // 显示大图
      knicking: false, // 正在踢人
      revoking: false, // 正在撤回消息
      memberDialog: false, // 正在撤回消息
      memberDetail: {}, // 群成员详情
      hb2detail: {}, // 群成员详情
    }
  },
  computed: {
    ...mapGetters({
      currentMode: 'currentMode',
      members: 'nedb/members',
      friends: 'nedb/friendsAll',
      currentChats: 'nedb/currentChats',
      luckMoneyMap: 'nedb/luckMoneyMap',
      detailUrl: 'conversation/url',
      hbDetail: 'conversation/hbDetail',
      atContent: 'conversation/content',
      currentWechat: 'conversation/currentWechat',
      currentFriends: 'conversation/currentFriends',
      currentWeChatId: 'conversation/currentWeChatId',
      rebatesChannel:"conversation/rebatesChannel",
      showAddWxPaymentcode:"conversation/showAddWxPaymentcode",
    }),
    currentFriend() {
      return this.currentFriends[this.currentWeChatId] || {}
    },
    // 陌生人map
    memberMap() {
      let mm = {}
      for (const member of this.members) {
        mm[member.Wxid] = member
      }
      return mm
    },
    // 好友map
    friendMap() {
      let fm = {}
      for (const friend of this.friends) {
        fm[friend.FriendId] = friend
      }
      return fm
    },
    // 默认显示10条聊天记录
    chats() {
      let chats = []
      chats = this.currentChats.slice(-this.size)
      for (const chat of chats) {
        if (new Date().getTime() - chat.CreateTime < 1000 * 60 * 2) {
          chat.canRevoke = true
        } else {
          chat.canRevoke = false
        }
      }
      return chats
    },
    // 显示红包详情
    hbDetailVisible: {
      get() {
        return this.$store.getters['conversation/hbDetailVisible']
      },
      set(v) {
        this.$store.commit('conversation/SET_HB_DETAIL_VISIBLE', v)
        if (!v) {
          this.$store.commit('conversation/SET_HB_DETAIL', {
            WeChatId: '', // 所属微信号
            Success: false,
            ErrMsg: '',
            HbUrl: '', //
            TotalNum: null, // 红包总个数
            TotalAmount: null, // 红包总金额
            RecNum: null, // 已收红包个数
            Records: [], // 已收红包个数
            RecAmount: null // 已收红包金额
          })
          this.hb2detail = {}
        }
      }
    }
  },
  methods: {
    errorHandler() {
      return true
    },
    // 获取聊天的头像
    getAvatar(chat) {
      // 自己发的消息
      if (chat.IsSend) {
        return this.currentWechat.Avatar || ''
      } else if (chat.FriendId.indexOf('@chatroom') > -1) {
        //   群消息
        let memberId = base64.decode(chat.Content).split(':')[0]
        if (this.friendMap[memberId]) {
          return this.friendMap[memberId].Avatar
        } else if (this.memberMap[memberId]) {
          return this.memberMap[memberId].Avatar
        } else {
          return ''
        }
      } else {
        // 好友的消息
        return this.currentFriend.Avatar
      }
    },
    // 获取群聊发言人的昵称
    getMemberName(content) {
      let memberId = base64.decode(content).split(':')[0]
      let name = memberId
      if (this.friendMap[memberId]) {
        name = this.friendMap[memberId].FriendNick
      } else if (this.memberMap[memberId]) {
        name = this.memberMap[memberId].Nickname
      }
      return name
    },
    // 成员详情
    showMemberDetail(chat) {
      if (this.currentFriend.UserName) {
        let member = base64.decode(chat.Content).split(':')[0]
        if (this.friendMap[member]) {
          this.memberDetail = this.friendMap[member]
        } else if (this.memberMap[member]) {
          this.memberDetail = {
            WeChatId: this.currentFriend.WeChatId,
            FriendId: member,
            Avatar: this.memberMap[member].Avatar ? this.memberMap[member].Avatar : '',
            FriendNick: this.memberMap[member].Nickname ? this.memberMap[member].Nickname : '',
            LabelIds: '',
          }
        } else {
          this.memberDetail = {
            WeChatId: this.currentFriend.WeChatId,
            FriendId: member,
            Avatar: '',
            FriendNick: '',
            LabelIds: '',
          }
        }
        this.memberDialog = true
      }
    },
    // 添加到通讯录
    addToAddress() {
      let content = {
        WeChatId: this.memberDetail.WeChatId, // 商家个人微信内部全局唯一识别码
        ChatroomId: this.currentFriend.UserName, // 所在的群聊id
        FriendId: this.memberDetail.FriendId, // 请求加好友微信内部全局唯一识别码
        Message: '', // 招呼语
        Remark: '', // 备注信息
      }
      this.$store.dispatch('websocket/AddFriendInChatRoomTask', content)
      this.memberDialog = false
      this.$message.info('指令已经下发！')
    },
    // 获取详情
    getMemberDetail() {
      let content = {
        wechatId: this.memberDetail.WeChatId,
        friendId: this.memberDetail.FriendId
      }
      this.$store.dispatch('websocket/RequestContactsInfoTask', content)
      this.memberDialog = false
      this.$message.info('指令已经下发！')
    },
    // base64解码 & 不同类型的消息解读
    decodeChat(chat) {
      let content = chat.Content
      let regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      let thumb = ''
      let str = ''
      let nickName = ''
      if (content) {
        content = base64.decode(chat.Content)
      }
      if (chat.FriendId.indexOf('@chatroom') > 0) {
        if (!content.startsWith('http')) {
          content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
        }
      }
      switch (chat.ContentType) {
        // 文本 1
        case 'Text':
        case 1:
          return phiz.qqFaceImgMap(content)
        // 图片 2
        case 'Picture':
        case 2:
          if (typeof (content) === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            if (jContent.Thumb && jContent.Thumb.startsWith('http')) {
              thumb = jContent.Thumb
            } else if (jContent.Url) {
              thumb = jContent.Url
            } else {
              thumb = require('assets/svg/conversation-image-error.svg')
            }
          } else {
            thumb = content
          }
          str = `<img class="chat-img" src="${thumb}" title="点击看大图" alt="图片"/>`
          return str
        // 语音 3
        case 'Voice':
        case 3:
          if (content.endsWith('.amr')) {
            thumb = content.replace(/.amr$/, '.mp3')
          } else {
            thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
          }
          str = ` <audio src="${thumb}" alt="语音" controls></audio>`
          return str
        // 视频 4
        case 'Video':
        case 4:
          if (typeof (content) === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            thumb = jContent.Thumb ? jContent.Thumb : require('assets/svg/conversation-image-error.svg')
            str =
              `<img class="chat-img" src="${thumb}"  alt="视频" />
               <i class="fa fa-play-circle-o fa-2x play-video" aria-hidden="true" title="点击播放"></i>`
          } else {
            thumb = content
            str =
              `<video class="video-box" src="${thumb}" type="video/mp4" alt="视频"></video>
               <i class="fa fa-play-circle-o fa-2x play-video" aria-hidden="true" title="点击播放"></i>`
          }
          return str
        // 系统消息 5 ok
        case 'System':
        case 5:
          return content
        // 链接消息 6
        case 'Link':
        case 6:
          if (typeof (content) === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            switch (jContent.TypeStr) {
              case '[链接]':
                str =
                  `
                        <span class="link-title">${jContent.Title}</span>
                        <div class="link-content">
                          <span class="link-des">${jContent.Des}</span>
                          <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                        </div>
                        <div class="link-type">${jContent.TypeStr}</div>
                        `
                break
              case '[聊天记录]':
                str =
                  `
                        <span class="link-title">${jContent.Title}</span>
                        <div class="link-content">
                         <span class="link-des">${jContent.Des}...</span>
                        </div>
                        <div class="link-type">${jContent.TypeStr}</div>
                        `
                break
              default:
                str = jContent
                break
            }
            return str
          } else {
            return content
          }
        // 扩展的链接消息（小程序分享等），内容为xml格式，暂未使用 7
        case 'LinkExt':
        case 7:
          return `LinkExt消息：${content}`
        // 文件 8
        case 'File':
        case 8:
          if (typeof (content) === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            let size = 0
            if (jContent.size) {
              if (jContent.size < 1024) {
                size = jContent.size + 'B'
              } else if (jContent.size < 1024 * 1024) {
                size = parseInt(jContent.size / 1024) + 'KB'
              } else {
                size = parseInt(jContent.size / (1024 * 1024)) + 'MB'
              }
            }
            let fileSize = jContent.Des ? jContent.Des.replace(/,.*/, '') : (jContent.size ? size : '')
            let fileTitle = jContent.Title ? jContent.Title : (jContent.name ? jContent.name : '')
            let fileType = jContent.Des ? jContent.Des.replace(/.*,/, '').trim() : (jContent.name ? jContent.name.replace(/.*\./, '') : '')
            let fileSource = jContent.Source ? jContent.Source : '手机'
            let fileIcon = 'fa-question-circle-o'
            switch (fileType) {
              case 'doc':
              case 'docx':
                fileIcon = 'fa-file-word-o'
                break
              case 'xls':
              case 'xlsx':
                fileIcon = 'fa-file-excel-o'
                break
              case 'ppt':
              case 'pptx':
                fileIcon = 'fa-file-powerpoint-o'
                break
              case 'zip':
              case 'rar':
                fileIcon = 'fa-file-archive-o'
                break
              case 'text':
              case 'txt':
                fileIcon = 'fa-file-text-o'
                break
              case 'mp3':
                fileIcon = 'fa-file-sound-o'
                break
              default:
                fileIcon = 'fa-question-circle-o'
                break
            }
            str = `
                  <span class="file-title">${fileTitle}</span>
                  <div class="file-content">
                    <span class="file-des">${fileSize}</span>
                    <i class="fa ${fileIcon} file-icon" aria-hidden="true"></i>
                  </div>
                  <div class="file-type">${fileSource}</div>
                `
            return str
          } else {
            return content
          }
        // 名片 9
        case 'NameCard':
        case 9:
          if (typeof (content) === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            thumb = jContent.HeadImg ? jContent.HeadImg : ''
            // if (!thumb) {
            //   let nameCardId = jContent.Username
            //   thumb = this.friendMap[]
            // }
            nickName = jContent.Nickname
          } else {
            thumb = this.friendMap[content] ? this.friendMap[content].Avatar : ''
            nickName = this.friendMap[content] ? this.friendMap[content].FriendNick : ''
          }
          str = `
                    <div class="namecard-info">
                      <img class="namecard-img" src="${thumb}" alt="好友头像" />
                      <span class="namecard-nickname ellipsis2">${nickName}</span>
                    </div>
                    <div class="namecard-tip">个人名片</div>
                  `
          return str
        // 位置信息 10
        case 'Location':
        case 10:
          return `位置消息：${content}`
        // 红包 11
        case 'LuckyMoney':
        case 11:
          {
            let wish = '恭喜发财，大吉大利'
            if (typeof (content) === 'string' && regJson.test(content)) {
              jContent = JSON.parse(content)
              wish = jContent.Title
            }
            let flag = this.luckMoneyMap[chat.msgSvrId] ? '已领取' : ''
            str = `
                    <div class="luck-info">
                      <span class="luck-img" > &nbsp;&nbsp;🧧 </span>
                      <span class="luck-wish ellipsis2" >${wish}</span>
                      <span class="luck-flag ellipsis2" >${flag}</span>
                    </div>
                    <div class="luckmoney-tip">微信红包</div>
                    `
            return str
          }
        // 转账 12
        case 'MoneyTrans':
        case 12:
          {
            if (typeof (content) === 'string' && regJson.test(content)) {
              jContent = JSON.parse(content)
            } else {
              jContent = content
            }
            let moneyTransFlag = ''
            let money = 0
            if (jContent.Feedesc) {
              money = jContent.Feedesc
            }
            switch (jContent.PaySubType) {
              case 1:
                if (chat.IsSend) {
                  moneyTransFlag = `转账给${this.currentFriend.FriendNick}`
                } else {
                  moneyTransFlag = '转账给你'
                }
                break
              case 3:
                moneyTransFlag = '已收钱'
                break
              default:
                break
            }
            let imgUrl = require('assets/svg/conversation-transfer-money.svg')

            if (jContent.PaySubType === 3) {
              str = `
                        <div class="moneytran-info">
                            <img class="moneytran-img" src="${imgUrl}" alt />
                            <span class="moneytran-feed" >${money}</span>
                            <span class="moneytran-flag">${moneyTransFlag}</span>
                            <span class="moneytran-flag"></span>
                        </div>
                        <div class="moneytran-tip">微信转账</div>
                    `
            } else {
              let flag = this.luckMoneyMap[chat.msgSvrId] ? '已被领取' : ''
              str = `
                        <div class="moneytran-info">
                            <img class="moneytran-img" src="${imgUrl}" alt />
                            <span class="moneytran-feed" >${money}</span>
                            <span class="moneytran-flag">${moneyTransFlag}</span>
                            <span class="moneytran-flag">${flag}</span>
                        </div>
                        <div class="moneytran-tip">微信转账</div>
                  `
            }
            return str
          }
        // 小程序 13
        case 'WeApp':
        case 13:
          {
            let appIcon = require('assets/svg/conversation-image-error.svg')
            let appSource = '无效小程序'
            let appTitle = '无效小程序'
            let appThumb = ''
            let appTypeStr = '小程序'

            if (typeof (content) === 'string' && regJson.test(content)) {
              jContent = JSON.parse(content)
              appIcon = jContent.Icon && typeof (jContent.Icon) !== 'undefined' ? jContent.Icon : require('assets/svg/conversation-image-error.svg')
              appSource = jContent.Source
              appTitle = jContent.Title || jContent.Des
              appThumb = jContent.Thumb
              appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
            }

            str = `
                  <div class="app-des">
                  <img class="app-icon" src="${appIcon}" alt="icon" />
                  <span class="app-source ellipsis">${appSource}</span>
                  </div>
                  <div class="app-title ellipsis">${appTitle}</div>
                  <img class="app-img" src="${appThumb}" />
                  <div class="app-typestr">${appTypeStr}</div>
                   `
            return str
          }
        // Emoji 14
        case 'Emoji':
        case 14:
          {
            let eMap = {
              'jsb_j.png': 'http://emoji.qpic.cn/wx_emoji/abG5b87mcOW7YxBZFZPZOBXUjE99n48g6Znn6zaUiaVRtxMBYaEEKoA/',
              'jsb_s.png': 'http://emoji.qpic.cn/wx_emoji/ARQOAfC52Cu6iczyCvLhibUNQxCialTeaeObDoEMsL7uJjyV5dqzCNCFQ/',
              'jsb_b.png': 'http://emoji.qpic.cn/wx_emoji/Ty7jp6YeVib7MibicS8eb9buorVCg7mYTFXxuEpVDyQMaqK6PUoOcGxbQ/',
              'dice_1.png': 'http://emoji.qpic.cn/wx_emoji/QsDXJwBwXEXGFwLHJCm6haBlFls30vzPQcZTib9dyhLiazKxoPX6kp0A/',
              'dice_2.png': 'http://emoji.qpic.cn/wx_emoji/YbCHM38dRYCIWbKmiaBrdnPrfuuwicLD2iacSWaPoAiaFrUySG87ELibOXQ/',
              'dice_3.png': 'http://emoji.qpic.cn/wx_emoji/lgVbvPFtzP8ytMiaKZMUoV3BXNPRfUaP69vozHfNarmX3MlTrgOhrkA/',
              'dice_4.png': 'http://emoji.qpic.cn/wx_emoji/zaBCJf5hVDn8NlibdrxV4NoPc12d28S7s67UCJqwynRmB0spdttIbeQ/',
              'dice_5.png': 'http://emoji.qpic.cn/wx_emoji/72IJJTdBzuibcxvnpFVicUAzCWRJC3cKhtkpMHTFejC2cyOeEGSHibTKw/',
              'dice_6.png': 'http://emoji.qpic.cn/wx_emoji/Jowow1icuI3XqtkFeQgIuzjIEYHdtJZictGFJjTsAFwW1g6cx1uTaQfw/'
            }
            if (eMap[content]) {
              content = eMap[content]
            }
            str = `<img class="chat-img" src="${content}" title="点击看大图" alt="图片"/>`
            return str
          }
        // 群管理消息 15
        case 'RoomManage':
        case 15:
          //   return content
          return "RoomManage"
        // 红包系统消息 16
        case 'Sys_LuckyMoney':
        case 16:
          return JSON.parse(base64.decode(chat.Content)).Title
        // 群系统消息 17 ok
        case 'RoomSystem':
        case 17:
          return JSON.parse(base64.decode(chat.Content)).title
        case 'NotifyMsg':
        case 21:
          //   return content
          jContent = JSON.parse(content)
          str =
            `
                      <span class="link-title">${jContent.source}</span>
                      <div class="link-content">
                       <span class="link-des">${jContent.title}...</span>
                      </div>
                      <div class="link-type">${jContent.des}</div>
                      `
          return str
        case 'BizLink':
          return content
        // 不支持的消息
        default:
          return `不支持的消息${chat.ContentType}：${content}`
      }
    },
    // 点击事件
    whatToDo(chat) {
      switch (chat.ContentType) {
        case 'Text':
        case 'Voice':
        case 'System':
          break
        // 获取大图|视频|文件地址
        case 'Picture':
        case 'Video':
        case 'File':
          this.showDetail(chat)
          break
        case 'Link':
        case 6:
          this.openLink(chat)
          break
        case 'LuckyMoney':
        case 'MoneyTrans':
          // 查看红包
          this.queryHbDetailTask(chat)
          break
        case 'WeApp':
        case 13:
          break
        default:
          break
      }
    },
    // scroll消息置底
    setBottom() {
      let docSC = document.getElementById('show-chat')
      if (docSC) {
        let sh = document.getElementById('show-chat').scrollHeight
        let ch = document.getElementById('show-chat').clientHeight
        document.getElementById('show-chat').scrollTop = sh - ch
      }
    },
    // 到顶分页加载chats
    newPage() {
      let st = document.getElementById('show-chat').scrollTop
      let sh = document.getElementById('show-chat').scrollHeight
      let ch = document.getElementById('show-chat').clientHeight
      if (st === 0 && sh > ch) {
        // this.page = this.page + 1
        if (this.size < this.currentChats.length) {
          this.size = this.size + 1
          setTimeout(() => {
            document.getElementById('show-chat').scrollTop = 5
          }, 100);
        } else {
          this.$message.warning('没有更多数据！')
        }
        // this.page = (this.page + 1) >= this.maxPage ? this.page : this.page + 1
      }
    },
    // 获取详情
    showDetail(chat) {
      let content = ''
      let regJson = new RegExp(/^{.+}$/)
      let url = ""

      content = base64.decode(chat.Content)
      if (chat.FriendId.indexOf('@chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
      }

      if (typeof (content) === 'string' && regJson.test(content)) {
        content = JSON.parse(content)
      }
      // 先看content中有没有url
      if (typeof (content) === 'object' && (content.Url || content.url)) {
        url = content.Url || content.url
      } else if (typeof (content) === 'string') {
        url = content
      }

      if (url) {
        this.$store.commit('conversation/SET_URL', url)
      } else {
        let msg = {}
        for (const key in chat) {
          if (chat.hasOwnProperty(key)) {
            msg[key] = chat[key]
          }
        }
        msg['Content'] = content
        // 再查本地数据库是否有url
        // this.$store.dispatch('nedb/QueryUrl', msg)
        this.$store.dispatch('websocket/RequestTalkDetailTask', msg)
      }
      // 显示窗口
      this.detailDialogVisible = true
    },
    // 关闭dialog之前 重置url
    handleDeatilClose(done) {
      this.$store.commit('conversation/SET_URL', '')
      done()
    },
    // 打开链接
    openLink(chat) {
      let content = ''
      let regJson = new RegExp(/^{.+}$/)
      content = base64.decode(chat.Content)
      if (chat.FriendId.indexOf('@chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
      }
      if (typeof (content) === 'string' && regJson.test(content)) {
        let jContent = JSON.parse(content)
        switch (jContent.TypeStr) {
          case '[链接]':
            if (jContent.Title === '邀请你加入群聊' || jContent.Title === '邀请您加入群聊') {
              let contentMsg = {
                WeChatId: chat.WeChatId, // 商家个人微信内部全局唯一识别码
                Talker: chat.FriendId, // 邀请者
                MsgSvrId: chat.msgSvrId, // 邀请消息的msgSvrId
                MsgContent: JSON.stringify(jContent), // 回传邀请信息的内容（json）
              }
              // 同意加入群聊
              this.$store.dispatch('websocket/AgreeJoinChatRoomTask', contentMsg)
            } else {
              let url = jContent.Url
              if (this.currentMode === 'electron') {
                const { shell } = window.require('electron')
                shell.openExternal(url)
              } else {
                var a = document.createElement('a');
                a.setAttribute('href', url);
                a.setAttribute('target', '_blank');
                a.setAttribute('id', 'js_a');
                //防止反复添加
                if (document.getElementById('js_a')) {
                  document.body.removeChild(document.getElementById('js_a'));
                }
                document.body.appendChild(a);
                a.click();
              }
            }
            break
          case '[聊天记录]':
            break
          default:
            break
        }
      }
    },
    // 查看红包详情
    queryHbDetailTask(chat) {
      this.hb2detail = chat
      let content = ''
      let regJson = new RegExp(/^{.+}$/)
      content = base64.decode(chat.Content)
      if (chat.FriendId.indexOf('@chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
      }
      if (typeof (content) === 'string' && regJson.test(content)) {
        content = JSON.parse(content)
      }
      if (!content.Key || !chat.WeChatId) return
      // 获取详情
      this.$store.dispatch('websocket/QueryHbDetailTask', {
        WeChatId: chat.WeChatId,
        HbUrl: content.Key
      })
      this.$message({
        type: 'info',
        message: '正在获取红包详情！',
        duration: 1000
      })
    },
    // 收红包
    takeLuckMoney(chat) {
      let content = ''
      let regJson = new RegExp(/^{.+}$/)
      content = base64.decode(chat.Content)

      if (chat.FriendId.indexOf('@chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
      }
      if (typeof (content) === 'string' && regJson.test(content)) {
        let jContent = JSON.parse(content)
        let time = parseInt(new Date().getTime() / 1000)
        if (chat.IsSend) {
          // 如果是收转账的提示 不做处理
          if (jContent.PaySubType && jContent.PaySubType === 3) {
            return
          }
        } else {
          // 判断是否打开过
          // 如果该消息已经打开
          if (this.luckMoneyMap[chat.msgSvrId]) {
            // 转账本身已经显示状态和金额 就不再弹框展示
            // 这是弹框展示红包的金额
            if (chat.ContentType === 'LuckyMoney') {
              let amount = 0
              amount = '￥：' + this.luckMoneyMap[chat.msgSvrId].Amount
              this.$alert('金额' + amount + ' 分', '已经打开', {
                confirmButtonText: '确定',
                callback: action => {
                  return true
                }
              })
            }
          } else {
            // 收转账的消息 不做处理
            if (chat.ContentType === 'MoneyTrans' && jContent.PaySubType === 3) return
            // 红包或者转账过期 不再处理
            if (time - content.InvalidTime >= 24 * 60 * 60) {
              this.$message.warning('已过期')
            } else {
              // 打开红包
              let msgContent = {
                WeChatId: chat.WeChatId,
                FriendId: chat.FriendId,
                MsgSvrId: chat.MsgSvrId ? chat.MsgSvrId : chat.msgSvrId,
                MsgKey: jContent.Key,
              }
              this.$store.dispatch('websocket/TakeLuckyMoneyTask', msgContent)
            }
          }
        }
      }
    },
    // 能转发
    canTransform(chat) {
      let validType = [1, 2, 3, 6, 13, 'Text', 'Picture', 'Voice', 'Link', 'WeApp']
      this.$message.info('改功能待实现！')
      if (validType.indexOf(chat.ContentType) >= 0) {
        // 能转发
      } else {
        // 不能转发
      }
    },
    // 添加收款码
    addWxPaymentcode(chat){
      let content = ''
      let regJson = new RegExp(/^{.+}$/)
      let url = ""

      content = base64.decode(chat.Content)
      if (chat.FriendId.indexOf('@chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
      }

      if (typeof (content) === 'string' && regJson.test(content)) {
        content = JSON.parse(content)
      }
      // 先看content中有没有url
      if (typeof (content) === 'object' && (content.Url || content.url||content.Thumb)) {
        url = content.Url || content.url || content.Thumb
      } else if (typeof (content) === 'string') {
        url = content
      }
      this.$store.commit('conversation/SET_REBATESCHANNELURL', url)
      this.$store.commit('conversation/SET_SHOWADDWXPAYMENTCODE', false)
      
    },
    // 消息撤回
    revokeMessageTask(chat) {
      if (new Date().getTime() - chat.CreateTime >= 1000 * 60 * 2) {
        this.$message.warning('消息发出超过2分钟，不能测回！')
        return
      }
      this.revoking = true
      setTimeout(() => {
        this.revoking = false
      }, 2000);
      this.$store.dispatch('websocket/RevokeMessageTask', chat)
    },
    // @群成员 该方法只支持@一个人 如果要同时@多人请修改逻辑
    atSomebody(chat) {
      let memberId = base64.decode(chat.Content).split(':')[0]
      let memberName = this.getMemberName(chat.Content)
      // 如果要@的人已经不在群聊
      if (this.currentFriend.MemberList.indexOf(memberId) < 0) {
        this.$message.warning('该成员已经不在群里！')
        return
      }
      this.$store.commit('conversation/SET_REMARK', memberId)
      // 这里的不是空格是\u2005
      this.$store.commit('conversation/SET_CONTENT', `${this.atContent}@${memberName}\u2005`)
    },
    // 踢人
    knickSomeBody(chat) {
      // 先判断该好友是否还在群里
      let memberId = base64.decode(chat.Content).split(':')[0]
      let memberName = this.getMemberName(chat.Content)
      // 如果要踢的人已经不在群聊
      if (this.currentFriend.MemberList.indexOf(memberId) < 0) {
        this.$message.warning('该成员已经不在群里！')
        return
      }
      this.$confirm(`是否确认删除成员 ${memberName} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.knicking = true
        let message = {
          WeChatId: this.currentWeChatId, //string 商家所属微信号
          ChatRoomId: this.currentFriend.UserName, //string 群聊id
          Action: 3, //EnumChatRoomAction 指令
          Content: memberId, //string 指令内容
        }
        this.$store.dispatch('websocket/ChatRoomActionTask', message)
        setTimeout(() => {
          this.knicking = false
        }, 2000);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // ===============================================================
    // 鼠标右键 废弃
    rightEvent(event, chat) {
      let top = event.pageY
      let left = event.pageX
      this.chatChose = chat
      this.showRight = false
      let re = document.getElementById('chatRightEvents')
      re.style.top = top + 'px'
      re.style.left = left + 'px'
      this.showRight = true
    },
    // 隐藏右键菜单 废弃
    hideRight() {
      this.showRight = false
      this.showAt = false
    },
    // 转发好友
    // tranformToFriends(chat) {
    //   this.SetChatToTrans(chat)
    //   this.SetDialog('TransMsgToFriend')
    // },
    // 转发到群
    // tranformToChatRooms(chat) {
    //   this.SetChatToTrans(chat)
    //   this.SetDialog('TransMsgToChatRoom')
    // },
  },
  watch: {
    currentFriend(val) {
      setTimeout(() => {
        this.setBottom()
      }, 100)
      this.size = 10
      this.$store.dispatch('nedb/SetCurrentChats', (JSON.stringify(val) !== '{}' && val.FriendId) ? val.FriendId : val.UserName)
    }
  },
}
</script>

<style lang="scss" scoped>
.show-chats {
  height: 65%;
  // width: 99%;
  overflow-x: hidden;
  overflow-y: scroll;

  .chat-item {
    display: flex;
    flex-direction: column;
    margin: 5px;

    .chat-time {
      width: 200px;
      height: 20px;
      font-size: 14px;
      line-height: 20px;
      border-radius: 5px;
      color: white;
      margin: 5px auto;
      align-self: center;
      text-align: center;
      background: #dadada;
    }

    .chat-content {
      display: flex;
      position: relative;
      padding-top: 10px;
      font-size: 12px;
      color: $font-color-base;

      .member-info {
        max-width: 60%;
        position: absolute;
        color: $font-color-2;
        top: 0;
        left: 48px;
      }
      .content-content {
        max-width: 60%;
        min-height: 40px;
        line-height: 25px;
        padding: 5px;
        margin-left: 7px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        position: relative;
        background: white;
        word-break: break-all;
        border: 1px solid #e7e7e7;

        ::v-deep .chat-img {
          width: 100px;
          height: auto;
        }
        .chat-picture {
          width: 100px;
          display: flex;
          align-items: center;
        }
        .chat-voice {
          width: 300px;
          max-width: 100%;
          display: flex;
          align-items: center;
        }
        ::v-deep .chat-video {
          display: flex;
          align-items: center;
          position: relative;
          .play-video {
            color: #98e165;
            position: absolute;
            font-size: 50px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            cursor: pointer;
          }
          .video-box {
            width: 100px;
            // max-width: 100%;
            height: auto;
          }
        }
        ::v-deep .chat-system {
          color: gray;
          a {
            color: #41c0fc;
          }
        }
        ::v-deep .chat-link {
          flex-direction: column;
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          .link-title {
            font-size: 16px;
            font-weight: 600;
          }
          .link-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .link-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 14px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }
            .link-img {
              max-width: 50px;
              max-height: 50px;
              min-height: 50px;
              min-width: 50px;
              border-radius: 5px;
            }
          }
          .link-type {
            color: #aaaaaa;
            margin-top: 5px;
            text-align: start;
            border-top: solid #e8eaec 1px;
          }
        }
        ::v-deep .chat-file {
          flex-direction: column;
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          .file-title {
            font-size: 16px;
            font-weight: 600;
          }
          .file-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .file-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 14px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }
            .file-icon {
              font-size: 30px;
              margin-right: 20px;
            }
          }
          .file-type {
            color: #aaaaaa;
            margin-top: 5px;
            text-align: start;
            border-top: solid #e8eaec 1px;
          }
        }
        ::v-deep .chat-app {
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          display: flex;
          flex-direction: column;
          .app-des {
            display: flex;
            .app-icon {
              width: 20px;
              height: 20px;
            }
            .app-source {
              width: 100%;
              font-size: 12px;
              margin-left: 5px;
              color: gray;
            }
          }
          .app-title {
            width: 100%;
            height: 30px;
            font-size: 14px;
            font-weight: 600;
            line-height: 30px;
          }
          .app-img {
            align-self: center;
            max-width: 200px;
          }
          .app-typestr {
            height: 25px;
            margin-top: 5px;
            line-height: 25px;
            color: gray;
            text-align: start;
            border-top: solid #aaaaaa 1px;
          }
        }
        ::v-deep .chat-namecard {
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          .namecard-info {
            display: flex;
            align-items: center;
            .namecard-img {
              height: 50px;
              width: 50px;
              min-width: 50px;
              border-radius: 5px;
            }
            .namecard-nickname {
              width: 250px;
              font-size: 14px;
              margin-left: 5px;
            }
          }
          .namecard-tip {
            color: gray;
            margin-top: 5px;
            border-top: #aaaaaa solid 1px;
          }
        }
        ::v-deep .chat-luckmoney {
          width: 300px;
          max-width: 100%;
          background: #fa9d3b;
          cursor: pointer;
          .luck-info {
            display: flex;
            align-items: center;
            height: 60px;
            width: 100%;
            .luck-img {
              max-width: 50px;
            }

            .wish-open {
              display: flex;
              flex-direction: column;
            }

            .luck-wish {
              width: 200px;
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }

            .luck-flag {
              width: 60px;
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }

            .money-opened {
              margin-left: 10px;
              color: white;
            }
          }
          .luckmoney-tip {
            color: gray;
            background: white;
            margin-top: 5px;
          }
          &:hover {
            background: rgba($color: #fa9d3b, $alpha: 0.9);
          }
        }
        ::v-deep .chat-moneytran {
          width: 300px;
          max-width: 100%;
          background: #fa9d3b;
          cursor: pointer;
          .moneytran-info {
            display: flex;
            align-items: center;
            height: 60px;
            width: 100%;
            .moneytran-img {
              max-width: 30px;
              margin-left: 10px;
            }
            .moneytran-feed,
            .moneytran-flag {
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }
          }
          .moneytran-tip {
            color: gray;
            background: white;
            margin-top: 5px;
          }
          &:hover {
            background: rgba($color: #fa9d3b, $alpha: 0.9);
          }
        }
      }

      .send-state {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .chat-room {
        margin-top: 20px;
      }
      .triangle {
        &::before {
          content: "";
          border: 6px solid transparent;
          border-right: 6px solid #e7e7e7;
          position: absolute;
          top: 10px;
          left: -13px;
        }
        &::after {
          content: "";
          border: 6px solid transparent;
          border-right: 6px solid white;
          position: absolute;
          top: 10px;
          left: -12px;
        }
        &:hover {
          background-color: #f6f6f6;
          &::after {
            content: "";
            border: 6px solid transparent;
            border-right: 6px solid #f6f6f6;
            position: absolute;
            top: 10px;
            left: -12px;
          }
        }
      }
      .triangle-send {
        margin-right: 7px;
        background: #9eea6a;
        &::before {
          content: "";
          border: 6px solid transparent;
          border-left: 6px solid #e7e7e7;
          position: absolute;
          top: 10px;
          right: -13px;
        }
        &::after {
          content: "";
          border: 6px solid transparent;
          border-left: 6px solid #9eea6a;
          position: absolute;
          top: 10px;
          right: -12px;
        }

        &:hover {
          background-color: #98e165;
          &::after {
            border-left: 6px solid #98e165;
          }
        }
      }
      .system-info {
        border: none;
        max-width: 80%;
        margin: 0 auto;
        background: inherit;
      }
    }

    .chat-content-send {
      flex-direction: row-reverse;
      //   border: solid blue 1px;
    }
  }
  ::v-deep .detail-dialog {
    overflow: hidden;
    .el-dialog {
      overflow: hidden;
      height: 500px;
      min-width: 500px;
      display: flex;
      flex-direction: column;

      .el-dialog__body {
        overflow: hidden;
        margin: auto;
        flex: 1 1 auto;
        display: flex;
        align-items: center;
        justify-content: center;

        .detail-dialog-img {
          @include scroll;
          max-height: 100%;
          max-width: 100%;
          overflow: auto;
        }
        .detail-dialog-video {
          max-height: 100%;
          width: auto;
        }
      }
    }
  }
  .chat-no {
    width: 100%;
    height: 100%;
    background-image: url(~@/assets/images/kdd64.png);
    background-repeat: no-repeat;
    background-color: $bg-color-content-base;
    background-position: center;
  }
  .member-detail {
    display: flex;
    flex-direction: column;
    ::v-deep .el-dialog {
      width: 500px;
      .el-dialog__body {
        padding: 20px;
      }
    }
    .member-detail-info {
      display: flex;
      .member-detail-text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 20px;
        overflow: hidden;
      }
    }
    .member-detail-btns {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;
    }
  }
  .hb-details {
    display: flex;
    flex-direction: column;
    ::v-deep .el-dialog {
      width: 500px;
      .el-dialog__body {
        padding: 20px;
      }
    }
    .hb-btns {
      margin-top: 10px;
    }
  }
}
</style>
